﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using OpenCvSharp;
using OpenCvSharp.ImgHash;
using System.Net;

namespace BlackList.Utils
{
    public class ImageUtils
    {
        public static double Compare_Hist(string imgFile1, string imgFile2)
        {
            var matA = Cv2.ImRead(imgFile1);
            var matB = Cv2.ImRead(imgFile2);
            // 拆分通道
            Cv2.Split(matA, out Mat[] matA_S);
            Cv2.Split(matB, out Mat[] matB_S);
            //直方图的像素范围   
            Rangef[] histRange = { new Rangef(0, 256) };
            //直方图数组大小
            int[] histSize = { 256 };
            //直方图输出数组
            Mat hist_A = new Mat();
            Mat hist_B = new Mat();
            bool uniform = true, accumulate = false;
            Cv2.CalcHist(matA_S, new int[] { 0, 1, 2 }, null, hist_A, 1, histSize, histRange, uniform, accumulate);
            Cv2.CalcHist(matB_S, new int[] { 0, 1, 2 }, null, hist_B, 1, histSize, histRange, uniform, accumulate);
            //归一化，排除图像分辨率不一致的影响
            Cv2.Normalize(hist_A, hist_A, 0, 1, NormTypes.MinMax, -1, null);
            Cv2.Normalize(hist_B, hist_B, 0, 1, NormTypes.MinMax, -1, null);
            //相关性比较
            var res = Cv2.CompareHist(hist_A, hist_B, HistCompMethods.Correl);
            return res;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">文件地址</param>
        /// <param name="filePath">文件完整路径</param>
        /// <returns></returns>
        public static string DownloadFile(string url,string filePath)
        {
          
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                WebClient wc = new WebClient();
             string fileName =$"{Guid.NewGuid().ToString("N")}.jpg";        //这里加上威信id   
         //   string fileName = biaoshi + ".jpg";        //这里加上威信id   
            string fileFullName = $"{filePath}/{fileName}";
            try
            {
                if (!File.Exists(fileFullName))
                {
                    wc.DownloadFile(url, fileFullName);
                }
            }
            catch (Exception ex) {
                string ab = ex.ToString();
            }
            return fileFullName;
        }
    }
}
